﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Core.CurrentFramework.Repository.Entity;
using Core.CurrentFramework.Service;
using Core.CurrentFramework.infrastructure;
using Core.CurrentFramework.Repository.Dto.Login;
using Microsoft.AspNetCore.Http;

namespace Core.CurrentFramework.ClientWeb.Areas.Users.Controllers
{
    [Area("Users")]
    public class LoginController : Controller
    {
        private readonly IUserManagement _userContext;

        public LoginController(IUserManagement userContext)
        {
            _userContext = userContext;
        }
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Login(LoginUser user)
        {
            if (user.Code.ToLower() != (HttpContext.Session.GetString("LoginValidateCode") ?? "").ToLower())
            {
                ModelState.AddModelError(nameof(user.Code), "验证码错误");
                return View("Index");
            }
            if (_userContext.LoginUser(user.Email, user.UserPwd) && ModelState.IsValid)
            {
                return RedirectToAction("Index", "Home", new { area = "Home" });
            }
            ModelState.AddModelError(nameof(user.UserPwd), "账号或者密码错误");
            return View("Index");
        }

        [HttpGet]
        public IActionResult Rigster()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Rigster(UsersInfo user)
        {
            if (ModelState.IsValid)
            {
                if (_userContext.RigsterUser(user) == 0)
                {
                    ModelState.AddModelError(nameof(user.FUserName), "身份信息重复，请注意身份证手机号邮箱地址");
                    return View();
                }
                return View("Index");
            }

            return View();
        }

        /// <summary>
        /// 获取图形验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task GetVerifyCode()
        {
            Response.ContentType = "image/jpeg";
            using (var stream = VerificationCodeHelper.Create(out string code))
            {
                var buffer = stream.ToArray();

                HttpContext.Session.SetString("LoginValidateCode", code);
                // 将验证码的token放入cookie
                Response.Cookies.Append("code", code);

                await Response.Body.WriteAsync(buffer, 0, buffer.Length);
            }
        }
    }
}